/*
 * Created on Mar 3, 2010
 */
package com.mgmaps.tools;

import java.io.*;
import com.mgmaps.utils.ExtLogger;

public class IOTools {
  
  // skip & read buffer size
  public static final int BUFSIZE = 4096;

  private IOTools() {
  }
  
  
  /**
   * Get the basename of a file.
   * @param s file name
   * @return the basename
   */
  public static String baseName(String s) {
    int index = s.lastIndexOf('/');
    if (index < 0)
      return s;
    else
      return s.substring(index+1);
  }
  
  
  /**
   * Read a line from the input stream.
   * 
   * @param is input stream to read from
   * @throws IOException if an error exception occurs
   */
  public static String readLine(InputStream is) throws IOException {
    StringBuffer sb = new StringBuffer();
    while(true) {
      int c = is.read();
      if (c == -1)
        break;
      if (c == '\n')
        break;
      if (c != '\r')
        sb.append((char) c);
    }
    return sb.toString();
  }
  
  
  /**
   * Read a line from the input stream.
   * 
   * @param r reader to read from
   * @throws IOException if an error exception occurs
   */
  public static String readLine(Reader r) throws IOException {
    StringBuffer sb = new StringBuffer();
    while(true) {
      int c = r.read();
      if (c == -1)
        return null;
      if (c == '\n')
        break;
      if (c != '\r')
        sb.append((char) c);
    }
    return sb.toString();
  }
  
  
  /**
   * Read all data from a reader.
   * @param r reader to read from
   * @return the data read
   * @throws IOException if an exception occurs
   */
  public static String readAll(Reader r) throws IOException {
    StringBuffer sb = new StringBuffer();
    while(true) {
      int c = r.read();
      if (c == -1)
        break;
      sb.append((char) c);
    }
    r.close();
    return sb.toString();
  }
  
  
  /**
   * Read all data from an input stream.
   * @param is input stream to read from
   * @return the data read
   * @throws IOException if an exception occurs
   */
  public static byte[] readAll(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[BUFSIZE];
    int ch = 0;
    do {
      ch = is.read(buf, 0, BUFSIZE);
      if (ch > 0)
        bos.write(buf, 0, ch);
    } while (ch > 0);
    buf = null;
    return bos.toByteArray();
  }
  

  /**
   * Open a UTF reader based on an input stream.
   * @param is input stream
   * @return the reader
   * @throws IOException if an exception occurs
   */
  public static InputStreamReader openUTFReader(InputStream is) throws IOException {
    InputStreamReader r = null;
    try {
      r = new InputStreamReader(is, "utf-8");
    }
    catch (Exception ex) {
      r = new InputStreamReader(is);
    }
    return r;
  }
  
  
  /**
   * Read "fully" some data from a stream.
   * @param is input stream
   * @param len length of data to read
   * @return the data read
   * @throws IOException if an exception occurs
   */
  public static byte[] readFully(InputStream is, int len) throws IOException {
    int ch = 0;
    int rd = 0;
    byte[] data = new byte[len];
    while ((rd != len) && (ch != -1)) {
      ch = is.read(data, rd, ((len-rd) < BUFSIZE ? (len-rd) : BUFSIZE));
      if (ch > 0)
        rd += ch;
    }
    return data;
  }

  
  /**
   * Write "fully" some data to a stream.
   * @param os output stream
   * @param data data
   * @throws IOException if an exception occurs
   */
  public static void writeFully(OutputStream os, byte[] data) throws IOException {
    int len = data.length;
    for (int wr = 0; wr < len; wr++) {
      int ch = ((len-wr) < BUFSIZE ? (len-wr) : BUFSIZE);
      os.write(data, wr, ch);
    }
  }

  
  /**
   * Load file from resources and return file contents.
   * @param filename file path
   * @return file contents
   */
  public static String loadFile(String filename) {
    InputStream is = null;
    Reader r = null;
    String content = null;
    try {
      is = new IOTools().getClass().getResourceAsStream(filename);
      r = openUTFReader(is);
      content = readAll(r);
    }
    catch (IOException ie) {
      ExtLogger.handle(ie, true, "Error reading file '" + filename + "'");
    }
    finally {
      // close the file
      if (is != null)
        try {
          is.close();
        }
        catch (IOException ie) {
        }
    }
    
    return content;
  }
  
}
